﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Mobile.Mvc;
using System.Windows.Forms;
using Microsoft.Practices.Mobile.ContainerModel;
using MultiPanelTest.Data;

namespace MultiPanelTest
{
    public class SearchController : Controller<Products>
    {

        [PublishEvent("OnProductsUpdated")]
        public event EventHandler ProductsUpdated;

        public SearchController(IView<Products> view)
            : base(view)
        {

            //// Create an intance of the Products
            //products = new Products();
            //// Populate the list
            //products.PopulateList();                        
            // Assign the Model
            //this.view.ViewData.Model = products;
            // Notify the view of the changes
            //this.NotifyView();

        }

        public Container Container
        {
            get;
            set;
        }

        // ViewLoaded event from the view
        private void OnViewLoaded(object sender, EventArgs e)
        {
            // Show busy cursor
            Cursor.Current = Cursors.WaitCursor;
            // Get an instance from the container
            Products products = this.Container.Resolve<Products>();
            // Populate data
            products.PopulateList();
            // Assign the Model
            this.view.ViewData.Model = products;
            // Notify the view of the changes
            this.NotifyView();
            // Restore the cursor
            Cursor.Current = Cursors.Default;
        }

        // Search event from the view
        private void OnSearch(object sender, DataEventArgs<string> e)
        {
            this.view.ViewData.Model.FilterData(e.Value);
            // Notify the view
            this.NotifyView();
        }

        // Selected event from the view
        private void OnSelected(object sender, DataEventArgs<Product> e)
        {
            this.ShowDetailView(e.Value);
        }

        // Selected event from the view
        private void OnBack(object sender, EventArgs e)
        {
            // Move back to the search form           
            this.Navigator.GoBack();
        }

        private void NotifyView()
        {
            // Raise the event for view
            if (this.ProductsUpdated != null)
            {
                this.ProductsUpdated(this, EventArgs.Empty);
            }
        }

        protected override void OnInitialize(params object[] parameters)
        {
            OnViewLoaded(null, null);           
        }

        private void ShowDetailView(Product product)
        {
            //DetailController controller = new DetailController(new DetailForm());
            //NavigationService.Navigate(controller, product);
           // this.Navigator.Navigate<DetailController>(product);
        }

    }
}
